//
//  SetPassWordViewController.m
//  ChengHuiTong
//
//  Created by ypwl on 15/11/13.
//  Copyright © 2015年 张文权. All rights reserved.
//

#import "SetPassWordViewController.h"

#import "TPKeyboardAvoidingScrollView.h"

#import "TPKeyboardAvoidingTableView.h"

#import "SetPassWordTableViewCell.h"

@interface SetPassWordViewController ()<UITableViewDataSource,UITableViewDelegate>
@end

@implementation SetPassWordViewController{
    
    
    NSString*_smsid;
    
    TPKeyboardAvoidingTableView*_TPKeyTableView;
    
    BOOL isReceive;

}

#pragma mark  生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    self.title=@"设置交易密码";
    
    [self creatAllView];
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark --UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 4;
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==1) {
        
        SetPassWordTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"cell1"];
        
        if (!cell) {
            cell=[[SetPassWordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
            
             cell.selectionStyle=0;
        }
        
        
        cell.titleLabel.text=@"验证码";
        
        cell.cellTextField.placeholder=@"输入验证码";
        
        cell.cellTextField.keyboardType=UIKeyboardTypePhonePad;
        
        cell.sendCodeButtonClickBlock=^(UIButton*button){
            
            
        [self sendButton:button];
            
        };
        
        
        
        return cell;
        
        
    }else if (indexPath.row==0){
        
        SetPassWordTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"cell2"];
        
        if (!cell) {
            
            cell=[[SetPassWordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
            
            cell.selectionStyle=0;
        }
        
        NSMutableString*phoneString=[[NSMutableString alloc] initWithString:[YPShareAccountInfo shareAccountInfo].phone];
        
        [phoneString replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        
        cell.phoneLabel.text=phoneString;
        
        cell.titleLabel.text=@"手机号";

        
        return cell;
        
        
    }
    
    
    else{
        
        SetPassWordTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"cell0"];
        
        if (!cell) {
            cell=[[SetPassWordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell0"];
            
            cell.selectionStyle=0;
        }
        
        
        if (indexPath.row==0) {
            
            
            
        }else{
            
            if (indexPath.row==2) {
                
                
                cell.titleLabel.text=@"新密码";
                
                cell.cellTextField.placeholder=@"请输入6-20位新密码";
                
                cell.cellTextField.secureTextEntry=YES;
                
               
            }
            
            if (indexPath.row==3) {
                
                cell.titleLabel.text=@"确认密码";
                
                cell.cellTextField.placeholder=@"请重复输入新密码";
 
                cell.cellTextField.secureTextEntry=YES;
                
               

            }
            
            
            
        }
        
        

        return cell;
    }
    
    
    
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 45;
}


-(void)viewDidLayoutSubviews

{
     [super viewDidLayoutSubviews];
    if ([_TPKeyTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_TPKeyTableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_TPKeyTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_TPKeyTableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}


#pragma mark 事件响应

-(void)sendButton:(UIButton*)button{
    
    if (isReceive==YES) {
        
        return;
    }
        
        __block int timeout=60;
    
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    
        dispatch_source_set_event_handler(_timer, ^{
            
            if(timeout<=0){
                
                dispatch_source_cancel(_timer);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [button setTitle:@"获取验证码" forState:UIControlStateNormal];
                   
                    
                    [button setBackgroundColor:[UIColor whiteColor]];
                    
                    [button setTitleColor:kColor_AppNavColor forState:0];
                    isReceive=NO;
                    
                    
                    
                });
                
            }else{
                
                int seconds = timeout % 61;
                
                NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    [button setTitle:[NSString stringWithFormat:@"重新发送(%@)",strTime] forState:UIControlStateNormal];
                   
                    [button setTitleColor:UIColorFromRGB(0xe4e3e2) forState:0];
                    
                    
                    if (isReceive==NO) {
                        
                        //发起请求
                        
                        [RequestModel sendCodeWithPhone:_phoneNumber SuccessBlock:^(id obj) {
                            
                            if ([obj[@"status"] intValue]==0) {
                                
                                _smsid=obj[@"smsid"];
                                
                            }else if ([obj[@"status"] intValue]==1005){
                                
                                [MBProgressHUD showError:@"手机号码无效" toView:self.view];
                                
                                 timeout=0;
                                
                            }else if ([obj[@"status"] intValue]==1309){
                                
                                [MBProgressHUD showError:@"发送短息失败" toView:self.view];

                                
                                 timeout=0;
                            }
                            
                            
                            
                        } failBlock:^(id obj) {
                            
                            [MBProgressHUD showError:@"网络链接失败" toView:self.view];
                            
                            timeout=0;
                            
                        }];
                        
                    }
                    
                    isReceive=YES;
                    
                });
                
                timeout--;
                
            }
            
        });
    
        dispatch_resume(_timer);
        
    

}

- (void)confirmButtonClick{
    
    SetPassWordTableViewCell*codecell=(SetPassWordTableViewCell*)[_TPKeyTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
     SetPassWordTableViewCell*passWordcell=(SetPassWordTableViewCell*)[_TPKeyTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
     SetPassWordTableViewCell*repeatcell=(SetPassWordTableViewCell*)[_TPKeyTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    
    
    if (codecell.cellTextField.text.length<1) {
        
        [MBProgressHUD showError:@"请输入验证码" toView:self.view];
       
        return;
    }
    
    if (passWordcell.cellTextField.text.length<1) {
        
        [MBProgressHUD showError:@"请输入新密码" toView:self.view];
        
        return;
    }
    
    if (repeatcell.cellTextField.text.length<1) {
        
         [MBProgressHUD showError:@"请确认新密码" toView:self.view];
        
        return;
    }
    
    if (passWordcell.cellTextField.text.length<6&&passWordcell.cellTextField.text.length>0) {
        
        [MBProgressHUD showError:@"密码长度小于6位" toView:self.view];

        return;
    }
    
    if (passWordcell.cellTextField.text.length>20) {
        
        [MBProgressHUD showError:@"密码长度大于20位" toView:self.view];

        return;
    }

    
    if (![passWordcell.cellTextField.text isEqualToString:repeatcell.cellTextField.text]) {
        
        [MBProgressHUD showError:@"两次密码不一致" toView:self.view];

        return;
    }
    
    
    
    
    [RequestModel sendCodeWithPassword:[GetCodeString getCodeWithString:passWordcell.cellTextField.text] code:codecell.cellTextField.text smsid:_smsid SuccessBlock:^(id obj) {
        
        
        if ([obj[@"status"] intValue]==0) {
            
            
            UIWindow*window=[UIApplication sharedApplication].keyWindow;
            
            [MBProgressHUD showError:@"设置成功" toView:window];
            
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }else if ([obj[@"status"] intValue]==1010){
            
            
            [MBProgressHUD showError:@"验证码已失效" toView:self.view];

        }else if ([obj[@"status"] intValue]==1011){
            
            
             [MBProgressHUD showError:@"验证码错误" toView:self.view];
        }
        
        
        
    
        
    } failBlock:^(id obj) {
        
        
        [MBProgressHUD showError:@"网络连接错误" toView:self.view];
    }];
    
    
}

#pragma UI

- (void)creatAllView{
    
   _TPKeyTableView=[[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, -10, SCREEN_WIDTH, SCREEN_HEIGHT-64+10) style:UITableViewStyleGrouped];
    
    _TPKeyTableView.delegate=self;
    
    _TPKeyTableView.dataSource=self;
    
    _TPKeyTableView.scrollEnabled=NO;
    
    
    [self.view addSubview:_TPKeyTableView];
    
    
    UIView*footView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    
    UIButton*confirmButton=[[UIButton alloc] initWithFrame:CGRectMake(40, 10, SCREEN_WIDTH-80, 35)];
    
    [confirmButton setTitle:@"确认提交" forState:0];
    
    [confirmButton setBackgroundColor:kColor_AppNavColor];
    
    confirmButton.layer.cornerRadius=3;
    
    
    confirmButton.titleLabel.font=[UIFont boldSystemFontOfSize:18];

    confirmButton.clipsToBounds=YES;
    
    [confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:confirmButton];
    
    _TPKeyTableView.tableFooterView=footView;
    
    
    
    
//    
//    TPKeyboardAvoidingScrollView*scrollView=[[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    
//    
//    
//    scrollView.showsHorizontalScrollIndicator=NO;
//    
//    scrollView.showsVerticalScrollIndicator=NO;
//    
//    scrollView.contentSize=CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
//    
//    [self.view addSubview:scrollView];
//    
//    
//    UILabel*phone=[[UILabel alloc] initWithFrame:CGRectMake(20, 20, 80, 40)];
//    
//    phone.text=@"手机号码:";
//    
//    phone.textAlignment=2;
//    
//    phone.font=[UIFont systemFontOfSize:14];
//    
//    [scrollView addSubview:phone];
//    
//    
//    _phoneNumTextField=[[UITextField alloc] initWithFrame:CGRectMake(phone.right+10, phone.top ,  SCREEN_WIDTH-40-10-phone.width, 40)];
//    NSMutableString*phoneString=[[NSMutableString alloc] initWithString:[YPShareAccountInfo shareAccountInfo].phone];
//    
//    [phoneString replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
//    
//    _phoneNumTextField.text=phoneString;
//    
//    _phoneNumTextField.enabled=NO;
//    
//    _phoneNumTextField.selected=NO;
//    
//    _phoneNumTextField.font=[UIFont systemFontOfSize:14];
//    
//    _phoneNumTextField.borderStyle=3;
//    
//    _phoneNumTextField.placeholder=@"";
//    
//   // _phoneNumTextField.backgroundColor=[UIColor lightGrayColor];
//    
//    [scrollView addSubview:_phoneNumTextField];
//    
//    _sendCodeButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    
//    
//    _sendCodeButton.frame=CGRectMake(_phoneNumTextField.left, _phoneNumTextField.bottom+15, _phoneNumTextField.width, _phoneNumTextField.height);
//    
//    [_sendCodeButton setTitle:@"获取短信验证码" forState:0];
//    
//    _sendCodeButton.titleLabel.font=[UIFont systemFontOfSize:14];
//    
//    [_sendCodeButton setBackgroundColor:[UIColor grayColor]];
//    
//    [_sendCodeButton addTarget:self action:@selector(sendButton:) forControlEvents:UIControlEventTouchUpInside];
//    
//    [scrollView addSubview:_sendCodeButton];
//    
//    
//    UILabel*codeLabel=[[UILabel alloc] initWithFrame:CGRectMake(phone.left, _sendCodeButton.bottom+15, phone.width, phone.height)];
//    
//    codeLabel.text=@"验证码:";
//    
//    codeLabel.textAlignment=2;
//    
//    codeLabel.font=[UIFont systemFontOfSize:14];
//    
//    [scrollView addSubview:codeLabel];
//    
//    
//    _codeTextField=[[UITextField alloc] initWithFrame:CGRectMake(_phoneNumTextField.left, codeLabel.top, _phoneNumTextField.width, _phoneNumTextField.height)];
//    
//    _codeTextField.borderStyle=3;
//    
//    _codeTextField.keyboardType=UIKeyboardTypeNumberPad;
//    
//    _codeTextField.font=[UIFont systemFontOfSize:14];
//    
//    _codeTextField.placeholder=@"请输入验证码";
//    
//    [scrollView addSubview:_codeTextField];
//    
//    
//    UILabel*passWordLabel=[[UILabel alloc] initWithFrame:CGRectMake(phone.left, _codeTextField.bottom+15, phone.width, phone.height)];
//    
//    passWordLabel.text=@"新密码";
//    
//    passWordLabel.textAlignment=2;
//    
//    passWordLabel.font=[UIFont systemFontOfSize:14];
//    
//    [scrollView addSubview:passWordLabel];
//    
//    
//    _passwordTextField=[[UITextField alloc] initWithFrame:CGRectMake(_phoneNumTextField.left, _codeTextField.bottom+15, _phoneNumTextField.width, _phoneNumTextField.height)];
//    
//    _passwordTextField.font=[UIFont systemFontOfSize:14];
//    
//    _passwordTextField.secureTextEntry=YES;
//    
//    _passwordTextField.borderStyle=3;
//    
//    _passwordTextField.placeholder=@"请输入6-20位密码";
//    
//    [scrollView addSubview:_passwordTextField];
//    
//    UILabel*confirmPassWordLabel=[[UILabel alloc] initWithFrame:CGRectMake(phone.left, _passwordTextField.bottom+15, phone.width, phone.height)];
//    
//    confirmPassWordLabel.text=@"确认新密码:";
//    
//    confirmPassWordLabel.textAlignment=2;
//    
//    confirmPassWordLabel.font=[UIFont systemFontOfSize:14];
//    
//    [scrollView addSubview:confirmPassWordLabel];
//    
//    
//    
//    _confirmTextField=[[UITextField alloc] initWithFrame:CGRectMake(_phoneNumTextField.left, _passwordTextField.bottom+15, _phoneNumTextField.width, _phoneNumTextField.height)];
//    
//    _confirmTextField.font=[UIFont systemFontOfSize:14];
//    
//    _confirmTextField.secureTextEntry=YES;
//    
//    _confirmTextField.borderStyle=3;
//    
//    _confirmTextField.placeholder=@"请重复输入密码";
//    
//    [scrollView addSubview:_confirmTextField];
//    
//    
//    
//    _conformButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    
//    _conformButton.frame=CGRectMake(_phoneNumTextField.left, _confirmTextField.bottom+15, _phoneNumTextField.width, _phoneNumTextField.height);
//    
//    [_conformButton setTitle:@"确认提交" forState:0];
//    
//    _conformButton.titleLabel.font=[UIFont systemFontOfSize:14];
//    
//    [_conformButton setBackgroundColor:[UIColor grayColor]];
//    
//    [_conformButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
//    
//    [scrollView addSubview:_conformButton];
    
    
    
    
    
    
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
